﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using UFIDA.U8.BJSOFT.LF.MES.WEBAPI.DBHelp;
using UFIDA.U8.BJSOFT.LF.MES.WEBAPI.Models;

namespace UFIDA.U8.BJSOFT.LF.MES.WEBAPI.Method
{

    public class AddCheckVouch
    {
        public static string DBname = ConfigurationManager.AppSettings["U8DBNAME"].ToString();
        public static string Insert(string filename, string jsons)
        {
			Result mr = new Result();
			List<ItemsItemR> lim = new List<ItemsItemR>();
			int row = 0;
			string res = "";
			bool flag = !string.IsNullOrEmpty(jsons);
			if (flag)
			{
				try
				{
					List<string> list = new List<string>();
					RD10 rd = JsonConvert.DeserializeObject<RD10>(jsons);
					string dCode = rd.dCode;
					if (string.IsNullOrEmpty(dCode))
					{
						row = 1;
						res += "外部系统单号不允许为空!检查dCode字段";
					}
					else
					{
						int ifex2 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
						{
							"select COUNT(*) from ",
							AddRD01.DBname,
							"..CheckVouch where cCVCode='",
							dCode,
							"'"
						})));
						if (ifex2 > 0)
						{
							row = 1;
							res = string.Concat(new string[]
							{
								res,
								"外部系统单号[",
								dCode,
								"]在U8系统已存在",
								filename,
								"信息!"
							});
						}
					}
					string cCode = rd.cCode;
                    if (string.IsNullOrEmpty(cCode))
                    {
						row = 1;
						res += "U8盘点单号不允许为空!检查cCode字段";
                    }
                    else
                    {
						int ifex=Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
						{
							"select COUNT(*) from ",
							AddRD01.DBname,
							"..CheckVouch where cCVCode='",
							cCode,
							"'"
						})));
                        if (ifex==0)
                        {
							row = 1;
							res += "单号["+cCode+"]在U8系统中未找到对应盘点单!检查cCode字段";
						}
					}
					string dDate = rd.dDate;
					if (!string.IsNullOrEmpty(dDate))
					{
						if (!PublicMet.IsDate(dDate))
						{
							row = 1;
							res += "审核日期格式不正确!例：[2024-11-12]";
						}
					}
					else
					{
						row = 1;
						res += "审核日期不允许为空！检查dDate字段";
					}
					string cHandler = rd.cHandler;
					bool flag13 = string.IsNullOrEmpty(cHandler);
					if (flag13)
					{
						row = 1;
						res += "审核人不允许为空!检查cHandler字段";
					}
					else
					{
						string cHandlers = PublicMet.CUSERNAME(cHandler);
						if (string.IsNullOrEmpty(cHandlers))
						{
							row = 1;
							res += "未找到编码为[" + cHandler + "]的审核人员!";
                        }
                        else
                        {
							cHandler = cHandlers;
                        }
					}
					string cAcc_Id = AddRD01.DBname.Substring(7, 3);
					string ID = "",sql="";
					if (row==0)
                    {
						ID =DBHelp.SQLHelper.GetString("select ID from "+DBname+"..CheckVouch where cCVCode='"+cCode+"'");
						sql = @"update " + DBname + "..CheckVouch set cAccounter='"+cHandler+ "',dveridate='"+dDate+ "',dnverifytime='"+dDate+"' where ID='"+ID+"' ";
						LogException.WriteiLog(filename, "语句:" + sql, LogException.ilog, false);
						list.Add(sql);
					}
					int RDC = 0,RDR=0;
                    //其他出入库单
                    #region 获取出入库单ID
                    int fidrd = 0;
					int cidrd = 0;
					sql = " select iFatherId,iChildId from UFSystem..UA_Identity where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ";
					DataTable dtidrd = SQLHelper.GetDataTable(sql);
					bool flag17 = dtidrd.Rows.Count > 0;
					if (flag17)
					{
						fidrd = Convert.ToInt32(dtidrd.Rows[0]["iFatherId"].ToString());
						cidrd = Convert.ToInt32(dtidrd.Rows[0]["iChildId"].ToString());
					}
					else
					{
						sql = " insert into UFSystem..UA_Identity (cAcc_Id,cVouchType,iFatherId,iChildId)  values('" + cAcc_Id + "','rd',0,0) ";
						SQLHelper.ExecuteSql(sql);
					}
					fidrd++;
					list.Add("update UFSystem..UA_Identity set iFatherId=iFatherId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
                    #endregion

                    string cWhCode = "", VT_ID = "", cDepCode = "", cIRdCode = "", cORdCode = "", cMaker = "", cMemo = "", csysbarcode = "";
					sql = "select cWhCode,cIRdCode,cORdCode,cMaker,cCVMemo,cDepCode from " + DBname + "..CheckVouch where ID=" + ID+"";
					DataTable dtc = DBHelp.SQLHelper.GetDataTable(sql);
                    if (dtc.Rows.Count>0)
                    {
						cWhCode = dtc.Rows[0]["cWhCode"].ToString();
						cIRdCode = dtc.Rows[0]["cIRdCode"].ToString();
						cORdCode = dtc.Rows[0]["cORdCode"].ToString();
						cMaker = dtc.Rows[0]["cMaker"].ToString();
						cMemo = dtc.Rows[0]["cCVMemo"].ToString();
						cDepCode = dtc.Rows[0]["cDepCode"].ToString();
					}
					//出库单主表
					string RDIDC = "1" + string.Format("{0:D9}", fidrd);
					VT_ID = "85";
					csysbarcode = "||st09|" + cCode;
					string csql = "insert into " + DBname + "..rdrecord09(ID,bRdFlag,cVouchType,cBusType,cBusCode,cSource,cWhCode,cdepcode,dDate,cCode,crdcode, " +
					   " bTransFlag,bpufirst,biafirst,VT_ID,bIsSTQc,bFromPreYear,bIsComplement,iDiscountTaxType,iBG_OverFlag,ControlResult,ireturncount, " +
					   " iverifystate,iswfcontrolled,bredvouch,iPrintCount,cMaker,dnmaketime,dVeriDate,cHandler,dnverifytime,cdefine10,csysbarcode,cMemo) " +
					   " values ( " + RDIDC + ",0,'09','盘亏出库','" + cCode+"','盘点','" + cWhCode + "'," + Method.PublicMet.setvalue(2, cDepCode) + ", " +
					   " '" + dDate + "','" + dCode + "','" + cORdCode + "',0,0,0,'" + VT_ID + "',0,0,0,0,0,-1,0,0,0,0,0,'" + cMaker + "', " +
					   " getdate(),'" + dDate + "','" + cHandler + "',getdate(),NULL,'" + csysbarcode + "'," + Method.PublicMet.setvalue(2, cMemo) + ") ";
					
					//入库单主表
					string RDIDR = "1" + string.Format("{0:D9}", fidrd+1);
					VT_ID = "67";
					csysbarcode = "||st08|" + cCode;
					string rsql = "insert into " + DBname + "..RdRecord08(VT_ID,ID,bRdFlag,cVouchType,cBusType,cBusCode,cSource,cWhCode,dDate,cCode,cRdCode,cDepCode,cMemo, " +
										  " bTransFlag,cMaker,bpufirst,biafirst,bIsSTQc, bOMFirst,bFromPreYear,bIsComplement,iDiscountTaxType,ireturncount," +
										  " iverifystate,iswfcontrolled, bredvouch,cSourceLs,iPrintCount,dVeriDate,cHandler,dnverifytime,cdefine10,csysbarcode ) " +
										   " values ('" + VT_ID + "', '" + RDIDR + "','1','08','盘盈入库','"+cCode+"','盘点','" + cWhCode + "', " +
										   " '" + dDate + "','" + dCode + "','" + cIRdCode + "'," + Method.PublicMet.setvalue(2, cDepCode) + ", " +
										   " " + Method.PublicMet.setvalue(2, cMemo) + ",0,'" + cMaker + "',0,0,0,0,0,0,0,0,0,0,0," +
										   " 1,0,convert(varchar(10),getdate(),23),'" + cHandler + "',convert(varchar(10),getdate(),120),NULL,'" + csysbarcode + "')";


					int cou = rd.Items.Count;
					for (int i = 0; i < cou; i++)
					{
						ItemsItemR mir = new ItemsItemR();
						string cInvCode = rd.Items[i].cInvCode;
						if (string.IsNullOrEmpty(cInvCode))
						{
							row = 1;
							res = res + "第[" + (i + 1).ToString() + "]行存货编码不允许为空!检查cInvCode字段";
						}
						else
						{
							int ifex7 = Convert.ToInt32(SQLHelper.GetString(string.Concat(new string[]
							{
								"select COUNT(*) from ",
								AddRD01.DBname,
								"..Inventory where cinvcode='",
								cInvCode,
								"'"
							})));
							bool flag22 = ifex7 == 0;
							if (flag22)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行存货编码[",
									cInvCode,
									"]在U8系统不存在!"
								});
							}
						}
						string iQuantity = rd.Items[i].iQuantity;
						bool flag23 = string.IsNullOrEmpty(iQuantity);
						if (flag23)
						{
							row = 1;
							res = res + "第[" + (i + 1).ToString() + "]行数量不允许为空!检查iQuantity字段!";
						}
						else
						{
							bool flag24 = !PublicMet.IsNumberic(iQuantity);
							if (flag24)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行数量[",
									iQuantity,
									"]非数字类型!"
								});
							}
						}
						string cBatch = rd.Items[i].cBatch;
						bool cba = Convert.ToBoolean(SQLHelper.GetString(string.Concat(new string[]
						{
							"select isnull(bInvBatch,0) from ",
							AddRD01.DBname,
							"..Inventory where cinvcode='",
							cInvCode,
							"'"
						})));
						if (cba)
						{
							bool flag26 = string.IsNullOrEmpty(cBatch);
							if (flag26)
							{
								row = 1;
								res = string.Concat(new string[]
								{
									res,
									"第[",
									(i + 1).ToString(),
									"]行存货[",
									cInvCode,
									"]进行批次管理,批次不允许为空,检查cBatch字段!"
								});
							}
						}
						if (!cba && !string.IsNullOrEmpty(cBatch))
						{
							row = 1;
							res += "第[" + (i + 1) + "]行存货[" + cInvCode + "]未进行批次管理，不允许传批号!检查cBatch字段!";
						}
						
						string cPosCode = rd.Items[i].cPosCode;
						string where = "and 1=1 ";
						string rres = "";
						if (!string.IsNullOrEmpty(cBatch))
						{
							where += " and cCVBatch='" + cBatch + "' ";
							rres += "，批次[" + cBatch + "]";
						}
						if (!string.IsNullOrEmpty(cPosCode))
						{
							where += "and cPosition='" + cPosCode + "' ";
							rres += "，货位[" + cPosCode + "]";
						}
						sql = "select * from  CheckVouchs where cinvcode='"+cInvCode+"'"+where;
						DataTable ds = DBHelp.SQLHelper.GetDataTable(sql);
                        if (ds.Rows.Count==0)
                        {
							row = 1;
							res += "["+filename+"]不存在此编码["+cInvCode+"]物料"+rres;
                        }
						if (row == 0)
						{
							int RowNoC = 0, RowNoR=0;
							sql = @"update " + DBname + @"..CheckVouchs set iCVCQuantity ='" + iQuantity + @"' where cInvCode='" + cInvCode + "'" + where;
                            LogException.WriteiLog(filename, "子表更新语句:" + sql, LogException.ilog, false);
                            list.Add(sql);
                            decimal iqty = Convert.ToDecimal(DBHelp.SQLHelper.GetString("select isnull(iCVQuantity,0) iCVQuantity from " + DBname + @"..CheckVouchs where cInvCode='"+cInvCode+"'" +where));
							if (Convert.ToDecimal(iQuantity)>iqty)//实盘比账面大入库
                            {
								RDR++;
								cidrd++;
								SQLHelper.ExecuteSql("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
								string autoid = "1" + string.Format("{0:D9}", cidrd);
								string cbsysbarcode = "||st08|" + dCode + "|" + (i + 1).ToString();
								string sqlunit = string.Concat(new string[]
								{
								"select  cSTComUnitCode,isnull(iChangRate,NULL) iChangRate   from ",
								AddRD01.DBname,
								"..inventory i  left join ",
								AddRD01.DBname,
								"..ComputationUnit c  on i.cSTComUnitCode=c.cComunitCode  where cinvcode='",
								cInvCode,
								"'"
								});
								LogException.WriteiLog(filename, "采购入库辅计量单位编码查询语句：" + sqlunit, LogException.ilog, false);
								DataTable dtiv = SQLHelper.GetDataTable(sqlunit);
								bool flag28 = dtiv.Rows.Count > 0;
								string cAssUnit;
								string iinvexchrate;
								if (flag28)
								{
									cAssUnit = "'" + dtiv.Rows[0]["cSTComUnitCode"].ToString() + "'";
									bool flag29 = !string.IsNullOrEmpty(dtiv.Rows[0]["iChangRate"].ToString());
									if (flag29)
									{
										iinvexchrate = (dtiv.Rows[0]["iChangRate"].ToString() ?? "");
									}
									else
									{
										iinvexchrate = "NULL";
									}
								}
								else
								{
									cAssUnit = "NULL";
									iinvexchrate = "NULL";
								}
								RowNoC++;
								sql = "insert into " + DBname + "..RdRecords08(AutoID,ID,cInvCode,iQuantity,iFlag,iNQuantity,bLPUseFree," +
								   " bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,irowno,iposflag,cPosition,cBatch,cbsysbarcode,cAssUnit ,iinvexchrate  ) " +
								   " values( '" + autoid + "','" + RDIDC + "','" + cInvCode + "','" + iQuantity + "',0,'" + iQuantity + "',0," +
								   " 1,0,0,0,'" + RowNoC + "',1,NULL," + Method.PublicMet.setvalue(2, cBatch) + ",'" + cbsysbarcode + "|" + RowNoC + "'," + cAssUnit + "," + iinvexchrate + " )";
								LogException.WriteiLog(filename, "RD08子表新增语句:" + sql, LogException.ilog, false);
								list.Add(sql);
								list.Add(string.Concat(new string[]
								{
								"insert into ",
								AddRD01.DBname,
								"..IA_ST_UnAccountVouch08(IDUN,IDSUN,cVouTypeUN,cBustypeUN) values ('",
								ID,
								"','",
								autoid,
								"','08','其他入库')"
								}));
							}
                            if (Convert.ToDecimal(iQuantity)<iqty)//实盘比账面小出库
                            {
								RDC++;
								cidrd++;
								RowNoR++;
								SQLHelper.ExecuteSql("update UFSystem..UA_Identity set iChildId=iChildId+1 where cAcc_Id='" + cAcc_Id + "' and cVouchType='rd' ");
								string autoid = "1" + string.Format("{0:D9}", cidrd);
								string cbsysbarcode = "||st09|" + cCode + "|" + (i + 1).ToString();
								string sqlunit = string.Concat(new string[]
								{
								"select  cSTComUnitCode,isnull(iChangRate,NULL) iChangRate   from ",
								AddRD01.DBname,
								"..inventory i  left join ",
								AddRD01.DBname,
								"..ComputationUnit c  on i.cSTComUnitCode=c.cComunitCode  where cinvcode='",
								cInvCode,
								"'"
								});
								LogException.WriteiLog(filename, "采购入库辅计量单位编码查询语句：" + sqlunit, LogException.ilog, false);
								DataTable dtiv = SQLHelper.GetDataTable(sqlunit);
								bool flag28 = dtiv.Rows.Count > 0;
								string cAssUnit;
								string iinvexchrate;
								if (flag28)
								{
									cAssUnit = "'" + dtiv.Rows[0]["cSTComUnitCode"].ToString() + "'";
									bool flag29 = !string.IsNullOrEmpty(dtiv.Rows[0]["iChangRate"].ToString());
									if (flag29)
									{
										iinvexchrate = (dtiv.Rows[0]["iChangRate"].ToString() ?? "");
									}
									else
									{
										iinvexchrate = "NULL";
									}
								}
								else
								{
									cAssUnit = "NULL";
									iinvexchrate = "NULL";
								}
								sql = @"insert into " + DBname + "..rdrecords09(AutoID,ID,cInvCode,iQuantity,irowno,iFlag,bLPUseFree," +
										  " iRSRowNO,iOriTrackID,bCosting,bVMIUsed,iExpiratDateCalcu,iordertype,cbatch,iposflag ,cPosition,cbsysbarcode,cAssUnit,iinvexchrate ) " +
										  " values( " + autoid + ",'" + ID + "','" + cInvCode + "','" + iQuantity + "','" + RowNoR + "',0,0," +
										  " 0,0,1,0,0,0," + Method.PublicMet.setvalue(2, cBatch) + ",1,NULL,'" + cbsysbarcode + "|" + RowNoR + "'," + cAssUnit + "," + iinvexchrate + " ) ";
								LogException.WriteiLog(filename, "RD09子表新增语句:" + sql, LogException.ilog, false);
								list.Add(sql);

								list.Add(string.Concat(new string[]
								{
								"insert into ",
								AddRD01.DBname,
								"..IA_ST_UnAccountVouch09(IDUN,IDSUN,cVouTypeUN,cBustypeUN) values ('",
								ID,
								"','",
								autoid,
								"','09','其他出库')"
								}));

							}
							mir.Autoid = "";
							mir.U8RowNo = (i + 1).ToString();
							mir.U8ID = "";
							lim.Add(mir);
						}
					}

                    if (RDC>0)
                    {
						list.Add(csql);
                    }
                    if (RDR>0)
                    {
						list.Add(rsql);
                    }
					bool flag30 = row == 0;
					if (flag30)
					{
						int count = SQLHelper.ExecuteSqlTran(list);
						bool flag31 = count > 0;
						if (flag31)
						{
							res += "盘点成功";
							mr.U8Code = dCode;
							mr.Items = lim;
							LogException.WriteiLog(filename, "盘点成功[" + dCode + "]", LogException.ilog, false);
						}
						else
						{
							row = 1;
							res += "盘点失败";
						}
					}
				}
				catch (Exception ex)
				{
					row = 1;
					LogException.WriteiLog(filename, "盘点异常:" + ex.Message, LogException.ilog, true);
					res = res + "失败:" + ex.Message;
				}
			}
			else
			{
				row = 1;
				res += "未传任何数据!";
			}
			bool flag32 = row == 1;
			if (flag32)
			{
				mr.Code = "500";
				mr.Msg = res;
			}
			else
			{
				mr.Code = "200";
				mr.Msg = res;
			}
			return JsonConvert.SerializeObject(mr);
		}


    }
}